/**
 * 封装一个自定义hooks
 * 把我们的列表通用的请求、分页、参数过滤等封装起来
 * 暴漏出去统一调用
 */

import { useEffect, useState } from 'react';
import { BaseListReponselist, BasePagination } from '../types';

import { Form, TablePaginationConfig } from 'antd';

interface UseFetchListProps<RequestParams, ResponseType> {
  api: (params: RequestParams & Omit<BasePagination, 'total'>) => Promise<BaseListReponselist<ResponseType>>;
}

/**
 * 泛型 RequestParams 过滤参数类型
 * 泛型 ResponseType 返回数据的类型
 * @returns
 */
export function useFetchList<RequestParams, ResponseType>(props: UseFetchListProps<RequestParams, ResponseType>) {
  const [form] = Form.useForm();
  /**
   * 分页参数
   */
  const [paginationParams, setPaginationParams] = useState<Omit<BasePagination, 'total'>>({
    page: 1,
    size: 3,
    order: 'createTime',
    sort: 'desc',
  });

  const [loading, setLoading] = useState(false);

  /**
   * 列表总数
   */
  const [total, setTotal] = useState(0);

  /**
   * 过滤参数
   */
  const [requestParams, setRequestParams] = useState<RequestParams>({} as RequestParams);

  const [tableData, setTableData] = useState<ResponseType[]>([]);

  useEffect(() => {
    fetchData();
  }, [paginationParams]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await props.api({
        ...paginationParams,
        ...requestParams,
      });

      setTableData(res.list);
      setTotal(res.pagination.total);
    } finally {
      setLoading(false);
    }
  };

  const paginationChange = (pagination: TablePaginationConfig) => {
    // 改变分页参数
    /**
     * setState 操作是一个异步操作
     * 所以无法直接在下一行拿到改变后的state
     * 如果想要拿到修改后的state，必须数据副作用里获取
     */
    setPaginationParams({
      ...paginationParams,
      page: pagination.current!,
    });
  };

  const search = () => {
    // const a = { name: '张三' };
    // const b = { name: '李四', age: 10 };
    // const c = { ...a, ...b };
    // console.log(c);
    setRequestParams({
      ...requestParams,
      ...form.getFieldsValue(),
    });
    setPaginationParams({
      ...paginationParams,
      page: 1,
    });
  };

  return {
    tableData,
    total,
    paginationParams,
    paginationChange,
    search,
    form,
    fetchData,
    loading,
  };
}
